package com.neighbor.neighborhooduser.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neighbor.neighborhooduser.pojo.SecurityQuestions;
import com.neighbor.neighborhooduser.service.ISecurityQuestionsService;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户安全问题表 前端控制器
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@RestController
@RequestMapping("/securityQuestions")
public class SecurityQuestionsController {

    @Autowired
    ISecurityQuestionsService securityQuestionsService; //安全问题表的代理对象

    /**
     *      在数据库中添加新的安全问题
     * @param securityQuestions 添加的安全问题对象
     * @return  添加成功与否
     */
    @RequestMapping("add")
    ResponseMsg add(@RequestBody SecurityQuestions securityQuestions){
        return securityQuestionsService.save(securityQuestions)?ResponseMsg.success("添加安全问题成功"):
                ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"添加安全问题失败");
    }

    /**
     *      根据用户id在数据库中查询安全问题
     * @param userId    用户id
     * @return  安全问题（List<SecurityQuestions>）
     */
    @RequestMapping("selQuestions")
    ResponseMsg selQuestions(Integer userId){
        QueryWrapper<SecurityQuestions> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<SecurityQuestions> securityQuestions = securityQuestionsService.list(wrapper);
        if(null != securityQuestions){
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"该用户的安全问题",securityQuestions);
        }
        return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"该用户安全问题数据有误");
    }

    /**
     * 验证安全问题答案
     * @param verifyData 验证数据，包含userId和answers列表
     * @return 验证结果
     */
    @RequestMapping("verifyAnswers")
    ResponseMsg verifyAnswers(@RequestBody Map<String, Object> verifyData) {
        try {
            // 提取用户ID
            Integer userId = (Integer) verifyData.get("userId");
            if (userId == null) {
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "用户ID不能为空");
            }

            // 提取答案列表
            List<Map<String, Object>> answers = (List<Map<String, Object>>) verifyData.get("answers");
            if (answers == null || answers.isEmpty()) {
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "安全问题答案不能为空");
            }

            // 查询用户的所有安全问题
            QueryWrapper<SecurityQuestions> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            List<SecurityQuestions> userQuestions = securityQuestionsService.list(wrapper);

            if (userQuestions == null || userQuestions.isEmpty()) {
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "该用户未设置安全问题");
            }

            // 验证每个问题的答案
            for (Map<String, Object> answerMap : answers) {
                Integer questionId = (Integer) answerMap.get("questionId");
                String userAnswer = (String) answerMap.get("answer");

                if (questionId == null || userAnswer == null || userAnswer.trim().isEmpty()) {
                    return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "问题ID和答案不能为空");
                }

                // 查找对应的问题
                SecurityQuestions question = userQuestions.stream()
                        .filter(q -> Objects.equals(q.getQuestionId(), questionId))
                        .findFirst()
                        .orElse(null);

                if (question == null) {
                    return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "问题ID不存在");
                }

                // 直接比较答案（不加密）
                if (!userAnswer.trim().equals(question.getAnswer())) {
                    return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "安全问题答案不正确");
                }
            }

            // 所有答案都正确
            return ResponseMsg.success("安全问题验证成功");

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR, "数据问题");
        }
    }
}